<?php
class TweetsController extends AppController {
    public $uses = array('Tweet', 'TwitterAccount', 'GrabTweet');
    public $components = array('OauthConsumer', 'TwitterText');
    public $helpers = array('TwitterText');
    public $requireTwitterAuth = array('inbox', 'info', 'rate_limit_status', 'replies', 'sent', 'tweets','grab');

    public function beforeFilter() {
        if (in_array($this->action, $this->requireTwitterAuth)) {
            if (!$this->_setOAuthCredentials()) {
                $this->Session->setFlash(__('Twitter login required.', true));
                $this->redirect(array('action'=>'index'));
            }
        }
        parent::beforeFilter();
    }

    protected function _setOAuthCredentials() {
        $key = $this->Session->read('TwitterToken.access.key');
        $secret = $this->Session->read('TwitterToken.access.secret');
        if (!empty($key) && !empty($secret)) {
            $this->Tweet->setOAuthCredentials($key, $secret);
            $this->TwitterAccount->setOAuthCredentials($key, $secret);
            return true;
        } 
        return false;
    }

    public function login() {
        $callback_url = Router::url(array('action'=>'twitter_callback'), true);
        $requestToken = $this->OauthConsumer->getRequestToken('Twitter', 'http://twitter.com/oauth/request_token', $callback_url);
        $this->Session->write('TwitterToken.request', $requestToken);
        $redirect = 'http://twitter.com/oauth/authorize?oauth_token=' . $requestToken->key;

        $this->redirect($redirect);
    }

    public function logout() {
        $this->Session->delete('TwitterToken');
        $this->Session->setFlash(__('Logout success.', true));
        $this->redirect(array('action'=>'index'));
    }

    public function twitter_callback() {
        if (isset($this->params['url']['denied'])) {
            $this->redirect(array('controller'=>'pages', 'action'=>'display', 'help', 'oauth', 'denied'));
        } 

        $requestToken = $this->Session->read('TwitterToken.request');
        $accessToken = $this->OauthConsumer->getAccessToken('Twitter', 'http://twitter.com/oauth/access_token', $requestToken);

        if ($accessToken !== false) {
            $this->Session->write('TwitterToken.access', array('key'=>$accessToken->key, 'secret'=>$accessToken->secret));
            $this->_setOAuthCredentials();
            $info = $this->TwitterAccount->getAccountInfo();
            $this->Session->write('TwitterAccount', $info);
            $this->redirect(array('action'=>'tweets'));
        } else {
            echo 'Error';
            exit;
        }
    }

    public function update() {
    }

    public function index() {
        if ($this->checkTwitterLogin()) {
            $this->redirect(array('action'=>'tweets'));
        }
    }

    public function tweets() {
        $params = $this->_getListParams();

        if (isset($this->params['twitter_id'])) {
            $id = $twitter_id = $this->params['twitter_id'];
            $params = array_merge($params, compact('id'));
            $this->set('twitter_id', $twitter_id);
            $tweets = $this->Tweet->getUserTimeline($params);
        } else {
            $tweets = $this->Tweet->getFriendsTimeline($params);
        }

        //pr($tweets);
        $this->set('tweets', $tweets);
    }

    public function replies() {
        $params = $this->_getListParams();

        $tweets = $this->Tweet->getReplies($params);
        $this->set('tweets', $tweets);
        $this->render('tweets');
    }

    function _getListParams() {
        $params = array('count'=>200);
        if (isset($this->params['named']['max_id'])) {
            $params['max_id'] = $this->params['named']['max_id'];
        } elseif (isset($this->params['named']['since_id'])) {
            $params['since_id'] = $this->params['named']['since_id'];
        }

        return $params;
    }

    public function inbox() {
        $params = $this->_getListParams();

        $messages = $this->Tweet->getReceivedMessages($params);
        $this->set('messages', $messages);
    }

    public function sent() {
        $params = $this->_getListParams();

        $messages = $this->TwitterAccount->getSentMessages($params);
        $this->set('messages', $messages);
    }

    public function favorites() {
    }

    public function profile() {
        pr($this->TwitterAccount->getAccountInfo());
        exit;
    } 

    public function search() {
    }

    public function settings() {
    }

    public function user() {
        $params = array();
        if (isset($this->params['twitter_id'])) {
            $id = $this->params['twitter_id'];
        }
        $params = array_merge($params, compact('id'));

        $tweets = $this->Tweet->getUserTimeline($params);
        $this->set('tweets', $tweets);
        $this->render('tweets');
    }

    public function rate_limit_status() {
        $status = $this->Tweet->getRateLimitStatus();
        $basetime = strtotime('2010-05-10 00:00:00');
        $time = time();
        $key = date('Y-m-d H:i:s', floor(($time - $basetime)/15)*15 + $basetime);
        $value = $status['remaining_hits'];

        $this->Session->write('RateLimitLog.'.$key, $value);
        $this->set('status', $status);
    }

    public function reset_session() {
        $this->Session->delete('RateLimitLog');
    }

    public function jsonp_test() {
    }

    protected function checkTwitterLogin() {
        return ($this->Session->check('TwitterToken.access.key') && $this->Session->check('TwitterToken.access.secret'));
    }

    public function grab() {
        $this->autoRender = false;
        echo '<h1>'.date('Y-m-d H:i:s').'</h1>';
        $params = $this->_getListParams();
        App::import('Helper', 'TwitterText');
        $TwitterText = new TwitterTextHelper;

        $tweets = $this->Tweet->getFriendsTimeline($params);
        foreach($tweets as $tweet) {
            $tweet['_id'] = $tweet['id'];
            $tweet = array_merge($tweet, $TwitterText->extract($tweet['text']));
            $this->GrabTweet->create(array('GrabTweet'=>$tweet));
            if ($this->GrabTweet->save()) 
            {
                pr($tweet);
                pr($tweet['id'] . ': saved');
            }
        }

        //pr($tweets);
        $this->set('tweets', $tweets);
    }
}
?>
